package com.xmb.common.interceptor;


import com.xmb.common.service.impl.SnowflakeIdWorkerImpl;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Properties;

/**
 * Created by lyndon on 2019/3/26.
 * 统一处理所有的insert请求
 */
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class PrepareInterceptor implements Interceptor {

    @Autowired
    private SnowflakeIdWorkerImpl snowflakeIdWorker;

    private final static String FIELD_ID = "id";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        try {
            Object parameter = invocation.getArgs()[1];
            Class classParameter = (Class) parameter.getClass();
            Field[] fields = classParameter.getDeclaredFields();
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
            SqlCommandType sqlCommandType  = mappedStatement.getSqlCommandType();
            Field field = Arrays.stream(fields)
                    .filter(f -> FIELD_ID.equalsIgnoreCase(f.getName()))
                    .findFirst()
                    .orElse(null);
            if (field != null) {
                field.setAccessible(true);
                if (SqlCommandType.INSERT.equals(sqlCommandType)) {
                    field.set(parameter, snowflakeIdWorker.getNextId());
                }
            }
        } catch (Exception e) {

        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }

}
